package com.xjc.common;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.converter.BpmnXMLConverter;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.validation.ProcessValidator;
import org.flowable.validation.ProcessValidatorFactory;
import org.flowable.validation.ValidationError;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * Description
 * </p>
 *
 * @author xiaojincai
 * @since 2025-06-11
 */
@Slf4j
public class BpmnValidateUtil {

    private static final BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter();

    public static BpmnModel convertToBpmnModel(MultipartFile bpmnXml) throws XMLStreamException, IOException {
        final InputStream inputStream = bpmnXml.getInputStream();
        final XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
        final InputStreamReader xmlIn = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        final XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn);
        return bpmnXMLConverter.convertToBpmnModel(xtr);
    }

    public static BpmnModel convertToBpmnModel(byte[] bpmnXml) throws XMLStreamException {
        final InputStream inputStream = new ByteArrayInputStream(bpmnXml);
        final XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
        final InputStreamReader xmlIn = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        final XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn);
        return bpmnXMLConverter.convertToBpmnModel(xtr);
    }

    public static boolean validateXmlByte(byte[] bpmnXml) {
        try {
            final BpmnModel bpmnModel = convertToBpmnModel(bpmnXml);

            return validModel(bpmnModel);
        } catch (Exception e) {
            log.error("模板验证失败：", e);
            return true;
        }
    }

    public static boolean validModel(BpmnModel bpmnModel) {
        //模板验证
        final ProcessValidator validator = new ProcessValidatorFactory().createDefaultProcessValidator();
        final List<ValidationError> errors = validator.validate(bpmnModel);
        if (CollectionUtil.isNotEmpty(errors)) {
            final StringBuilder sb = new StringBuilder();
            errors.forEach(ve -> sb.append(ve.toString()).append("/n"));
            log.error("模板验证失败：{}", sb);
            return true;
        }
        return false;
    }

}
